<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline" ref="queryRef">
      <el-form-item label="姓名">
        <el-input v-model="queryParams.nickName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="所属机构">
        <el-input v-model="queryParams.relatedRemark" placeholder="请输入机构名称" />
      </el-form-item>
      <el-form-item label="启用状态">
        <el-select class="w-30" v-model="queryParams.enabled" placeholder="请选择启用状态">
          <el-option
              v-for="dict in yesOrNo"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="queryParams.createTimeRange"
            type="daterange"
            range-separator="至"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加机构用户</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户列表 -->
    <el-table v-loading="loading" :data="userList" border stripe>
      <el-table-column prop="userId" label="用户编号" width="180" />
      <el-table-column prop="phonenumber" label="手机号码" />
      <el-table-column prop="roleName" label="所属角色" />
      <el-table-column prop="nickName" label="姓名" />
      <el-table-column prop="sex" label="性别" >
      <template #default="scope">
        <dict-tag :options="gender" :value="scope.row.sex" />
      </template>
      </el-table-column>
      <el-table-column prop="audit" label="审核状态" />
      <el-table-column prop="relatedRemark" label="所属机构" />
      <el-table-column prop="relatedId" label="所属机构ID" v-if="columns[0].visible" />
      <el-table-column prop="enabled" label="启用状态" >
      <template #default="scope">
        <dict-tag :options="yesOrNo" :value="scope.row.enabled" />
      </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:user:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:user:remove']"></el-button>
          </el-tooltip>
          <el-tooltip content="重置密码" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)"
                       v-hasPermi="['system:user:resetPwd']"></el-button>
          </el-tooltip>
          <el-tooltip content="分配角色" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)"
                       v-hasPermi="['system:user:edit']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20"
                        show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{
                    dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName"
                           :value="item.postId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
                           :value="item.roleId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构">
              <el-select v-model="form.relatedId"  filterable placeholder="请选择">
                <el-option v-for="item in organizationOptions" :key="item.id" :label="item.orgName"
                           :value="item.id" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { listUsers, addJgUser, getUser, updateUser,deptTreeSelect,delUser,resetUserPwd } from "@/api/system/user"; // 注意：需引入 add/edit API

// 路由实例
const router = useRouter();
const { proxy } = getCurrentInstance()
const {
  yesOrNo,gender,sys_user_sex,sys_normal_disable
} = proxy.useDict('yesOrNo','gender','sys_user_sex','sys_normal_disable')


// 弹窗相关
const formVisible = ref(false);        // 是否显示弹窗
const formTitle = ref('');             // 弹窗标题
const isEdit = ref(false);             // 是否为编辑模式
const queryRef = ref(null); // 用于引用查询表单
const title = ref("")
const open = ref(false)
const ids = ref([])
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const initPassword = ref(undefined)
const postOptions = ref([])
const roleOptions = ref([])
const organizationOptions = ref([])

const data = reactive({
  form: {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    userType: 1,
    remark: undefined,
    postIds: [],   // 明确初始化
    roleIds: [],   // 明确初始化
    relatedId: undefined,
    // 其他可能需要的字段
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
    userType: 1,
    // 查询专用字段
    nickName: undefined,
    relatedRemark: undefined,
    enabled: undefined,
    createTimeRange: [],
    beginTime: undefined,
    endTime: undefined
  },
  rules: {
    nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phonenumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 列显隐信息
const columns = ref([
  { key: 0, label: `机构用户ID`, visible: false },
])

// 表单数据（根据你列表展示字段设计）
const formData = reactive({
  phonenumber: '',     // 手机号码
  roleName: '',        // 所属角色（若为下拉，需字典或远程加载）
  nickName: '',        // 姓名
  sex: '',             // 性别
  relatedRemark: '',   // 所属机构
  status: '0'          // 启用状态，默认正常
});

// 数据列表与总数
const userList = ref([]);
const total = ref(0);
const loading = ref(true)

// 机构类型字典（示例数据，实际应从 API 或全局字典获取）
const organizationType = ref([
  { value: '0', label: '正常' },
  { value: '1', label: '停用' }
  // 根据实际业务补充更多状态
]);

// 获取用户列表
const getList = () => {
  loading.value = true
  listUsers(queryParams.value).then(response => {
    userList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false
  })
};

// 查询操作
const handleQuery = () => {

  // 处理时间范围
  if (queryParams.value.createTimeRange && queryParams.value.createTimeRange.length === 2) {
    queryParams.value.beginTime = queryParams.value.createTimeRange[0] + " 00:00:00";
    queryParams.value.endTime = queryParams.value.createTimeRange[1] + " 23:59:59";
  } else {
    queryParams.value.beginTime = undefined;
    queryParams.value.endTime = undefined;
  }

  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
// 重置查询
const resetQuery = () => {
  // 重置 queryParams 的值
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
    userType: 2,
    nickName: undefined,
    relatedRemark: undefined,
    enabled: undefined,
    createTimeRange: [],
    beginTime: undefined,
    endTime: undefined
  };
  // 或者逐个赋值
  // queryParams.value.nickName = ''
  // queryParams.value.relatedRemark = ''
  // ...

  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  handleQuery(); // 重新查询
};


// 页面加载时获取数据
onMounted(() => {
  getDeptTree()
  getList();
  proxy.getConfigKey("sys.user.initPassword").then(response => {
    initPassword.value = response.msg
  })
});

// 添加机构用户（打开对话框）
const handleAddJgyh = () => {
  resetForm(); // 重置表单
  formTitle.value = '添加机构用户';
  formVisible.value = true;
  isEdit.value = false;
};

// 重置表单
const resetForm = () => {
  formData.id = undefined;
  for (const key in formData) {
    formData[key] = '';
  }
  formData.status = '0'; // 默认正常
  if (proxy.$refs.userFormRef) {
    proxy.$refs.userFormRef.resetFields();
  }
};

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getUser().then(response => {
    postOptions.value = response.posts
    roleOptions.value = response.roles
    organizationOptions.value = response.organizations
    open.value = true
    title.value = "添加用户"
    form.value.password = initPassword.value
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const userId = row.userId || ids.value
  getUser(userId).then(response => {
    form.value = response.data
    postOptions.value = response.posts
    roleOptions.value = response.roles
    organizationOptions.value = response.organizations
    form.value.postIds = response.postIds
    form.value.roleIds = response.roleIds
    form.value.relatedId = response.relatedId
    open.value = true
    title.value = "修改用户"
    form.password = ""
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addJgUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    userType: 1,
    remark: undefined,
    postIds: [],
    roleIds: [],
    relatedId: undefined
  }
  proxy.resetForm("userRef")
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value
  proxy.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId
  router.push("/system/user-auth/role/" + userId)
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.nickName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return "不能包含非法字符：< > \" ' \\\ |"
      }
    },
  }).then(({ value }) => {
    resetUserPwd(row.userId, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value)
    })
  }).catch(() => { })
}

</script>

<style scoped>
/* 可添加自定义样式 */
.demo-form-inline {
  margin-bottom: 16px;
}
</style>
